<?php

/**
 * 调试信息输出
 * @param $args
 * @param bool $exit
 */
function mydebug($args , $exit = true){
	echo '<pre>';
	echo '<meta charset="utf-8">';
	print_r($args);
	echo '</pre>';
	$exit && exit;
}


/**
 * 记文件形式调试信息,也可用于记录日志
 * @param $data //内容
 * @param string $filepath 文件存放路径 如为 ./log或log则为日志记录,自动加上日期文件夹
 */
function filedebug($data , $filepath='./filedebug.php'){
	// 如果是日志，则将日志分隔成日期文件夹
	$date = date('Ym/d');
	$filepath = str_replace('log/' , "log/$date/" , $filepath);
	$have = strripos($filepath , '/');
	$path = (false === $have ? '' :  substr($filepath , 0 , $have+1)); // 文件夹
	$filearr=explode('/',$filepath);
	$file = end($filearr) ?:'default.php'; // 文件名
	if($path && !is_dir($path)){
		mkdir($path,0777,true);
	}
	$filepath = $path . $file;
	$f = fopen($filepath , 'a+');
	fwrite($f , date('Y-m-d H:i:s').'----------'."\n");
	fwrite($f , var_export($data , true));
	fwrite($f , "\n".'----------');
	fclose($f);
}

// 得到客户端ip
function getIp() {
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP");
	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR");
	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR");
	else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR'];
	else $ip = "127.0.0.1";
	return ($ip);
}

// 生成 guid / uuid
function guid(){
	if (function_exists('com_create_guid')){
		return trim(com_create_guid(),'{}"');
	}else{
		mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
		$charid = strtoupper(md5(uniqid(rand(), true)));
		$hyphen = chr(45);// "-"
//		$uuid = chr(123)// "{"
//			.substr($charid, 0, 8).$hyphen
//			.substr($charid, 8, 4).$hyphen
//			.substr($charid,12, 4).$hyphen
//			.substr($charid,16, 4).$hyphen
//			.substr($charid,20,12)
//			.chr(125);// "}"
		$uuid = substr($charid, 0, 9).$hyphen
			.substr($charid, 8, 4).$hyphen
			.substr($charid,12, 4).$hyphen
			.substr($charid,16, 4).$hyphen
			.substr($charid,19,12);
		return $uuid;
	}
}

/**
 * @param $proArr	// 一个一维数组
 * @return int|string
 * 一个随机算法
 */
function get_rand($proArr) {
	$result = '';
	
	//概率数组的总概率精度
	$proSum = array_sum($proArr) * 10;
	
	//概率数组循环
	foreach ($proArr as $key => $proCur) {
		$randNum = mt_rand(1, $proSum);
		$proCur *= 10;
		if ($randNum <= $proCur) {
			$result = $key;
			break;
		} else {
			$proSum -= $proCur;
		}
	}
	unset ($proArr);
	
	return $result;
}

/**
 * 将数据导出EXCEL
 * @param  [array 一维数组] $title   [标题]
 * @param  [array 二维数组] $content [导出内容]
 * @param  [string] $filename [文件名,默认为data.xls]
 */
function exportData($title , $content , $filename = 'data'){
//	$title = array('标题a' , '标题b' , '标题c');
//	$content = array(
//		array('aa' , 'bb' , 'cc'),
//		array('dd' , 'ee' , 'ff'),
//		array('gg' , 'hh' , 'ii'),
//	);
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition: attachment; filename=' . $filename . '.xls');
	header('Pragma: no-cache');
	header('Expires: 0');

	echo iconv('utf-8', 'gbk', implode("\t", $title)), "\n";
	foreach ($content as $value) {
		echo iconv('utf-8', 'gbk', implode("\t", $value)), "\n";
	}
	exit();
}

/**
 * 添加压缩包
 * @param $file 目标压缩包路径
 * @param $filename 待添加至压缩包的文件路径
 */
function addZip($file,$filename){
	if(!$file || !$filename){
		return false;
	}
	//实例化类
	$zip = new ZipArchive();
	//需要打开的zip文件,文件不存在将会自动创建

	if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
		//如果是Linux系统，需要保证服务器开放了文件写权限
		exit("文件打开失败!");
	}

	//将test.php文件添加到压缩文件中
	$zip->addFile($file);

//	//输出加入的文件数 , 这里应该是 2
//	echo "文件数 : ".$zip->numFiles;

	//关闭文件
	$zip->close();
}

/**
 * @param $time
 * @return bool|string
 * 时间格式化
 */
function time2date($time){
	if(!$time) return 0;
	$date = date('Y-m-d H:i:s',$time);
	return $date;
}
function time2date_date($time){
	if(!$time) return 0;
	$date = date('Y-m-d',$time);
	return $date;
}
function time2zh($time){
	$now_time = NOW_TIME;
	$zh = time2date($time);
	$diff = $now_time - $time;
	if($diff < 60){
		$zh = $diff.' 秒前';
	}elseif($diff < 3600){
		$zh = floor($diff/60).' 分钟前';
	}elseif($diff < 3600 * 24) {
		$zh = floor($diff/3600).' 小时前';
	}elseif($diff < 3600 * 24 * 7){
		$zh = floor($diff/86400).' 天前';
	}
	return $zh;
}
function expire2zh($expire_time){
	$now_time = NOW_TIME;
	// 过期时间减去当前时间，得到剩余秒数
	$cha = $expire_time - $now_time;
	if($cha <= 0){
		$zh = '<div class="time gray" style="background-color:#666666;">过期';
		$tian = ceil(-$cha / 86400);
	}else{
		$zh = '<div class="time">剩余';
		$tian = ceil($cha / 86400);
	}
	return $zh.' '.$tian.' 天</div>';
}

/**
 * 将php对象转为数组
 * @param $object
 * @return mixed
 */
function object2array($object) {
	if (is_object($object)) {
		foreach ($object as $key => $value) {
			$array[$key] = $value;
		}
	}
	else {
		$array = $object;
	}
	return $array;
}

/**
 * 将对象转为php数组
 * @param $array
 * @return StdClass
 */
function array2object($array) {
	if (is_array($array)) {
		$obj = new StdClass();
		foreach ($array as $key => $val){
			$obj->$key = $val;
		}
	}
	else {
		$obj = $array;
	}
	return $obj;
}

//url base64编码
function urlsafe_b64encode($string) {
	$data = base64_encode($string);
	$data = str_replace(array('+','/','='),array('-','_',''),$data);
	return $data;
}
//url base64解码
function urlsafe_b64decode($string) {
	$data = str_replace(array('-','_'),array('+','/'),$string);
	$mod4 = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	return base64_decode($data);
}

//字符串转十六进制
function strToHex($string){
	$hex="";
	for($i=0;$i<strlen($string);$i++)
		$hex.=dechex(ord($string[$i]));
	$hex=strtoupper($hex);
	return $hex;
}

//十六进制转字符串
function hexToStr($hex){
	$string="";
	for($i=0;$i<strlen($hex)-1;$i+=2)
		$string.=chr(hexdec($hex[$i].$hex[$i+1]));
	return  $string;
}

// 模板自动指定名称
function views($blade_name = null,$data = []){
	if(empty($blade_name)){
		$module = substr(strrchr(Route::current()->getAction()['namespace'],'\\'),1);
		$route = Route::current()->uri();
		$blade_name = strtolower($module.'.'.str_replace('/','.',$route));
	}
	return view($blade_name,$data);
}


//js跳转
function jq_redirect($url){
	echo "<scritp language='javascript' type='text/javascript'> location.href=".$url.";</scritp>";
}

// base64 上传图片
function base64_upload($type,$field,$callback = ''){
	$sBase64 = request($field);
	$file_name_pre = '/storage/'.$type.'/'.date('Y-m-d').'/';
	$return = array();
	if(empty($sBase64)){
		@$callback([]);
		return false;
	}
	if(!is_array($sBase64)){
		$sBase64 = array($sBase64);
	}
	foreach($sBase64 as $base64){
		if(strpos($base64 , "base64,")){
			$base64 = explode('base64,' , $base64)[1];
		}
		$base64 = base64_decode($base64);
		if(empty($base64)) continue;
		
		$file_name = $file_name_pre.uniqid(date('Ymd').rand('1000','9999')).'.png';
		$save_path = '.'.$file_name;
		if(!is_dir('.'.$file_name_pre)){
			mkdir('.'.$file_name_pre,0777,true);
		}
		file_put_contents($save_path,$base64);
		$return[] = $file_name;
	}
	@$callback($return);
	return true;
}

/**
 * @param $files
 * @return mixed
 * 上传到文件服务器
 */
function curl_upfile($files){
	$ch = curl_init();
	$post = array();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Content-Type: multipart/form-data'));
	curl_setopt($ch, CURLOPT_URL,env('FILE_SERVER_URL'));
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// same as <input type="file" name="file_box">
	$post = array(
		'AppId'		=> env('FILE_SERVER_APPID'),
		'SafeCode'	=> env('FILE_SERVER_SAFECODE'),
		'Thumnail'	=> '0',
//		'file_box'	=> "@".getcwd().$files,
		'image[]'	=> curl_file_create(getcwd().$files),
	);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	$response = curl_exec($ch);
	if(curl_errno($ch)){	//出错则显示错误信息
		throw new Exception('上传图片文件过大');
	}
	curl_close($ch); //关闭curl链接
	unlink(getcwd().$files);
	preg_match('/<fullpath.*fullpath>/i',$response,$match);
	return strip_tags($match[0]);
}

	/**
	 * 记录用户行为日志
	 **/
	function record_action($action_id,$controller='',$action='',$remark='',$request_info='') {
		//获取管理员信息
		$node_id = $_SESSION['admin_uid'];
		$node_info = DB::table('tnet_reginfo')
					 ->where(['nodeid'=>$node_id])
					 ->first();
		//记录用户行为信息
		$data['action_id'] 	  = $action_id;
		$data['node_id']      = $node_id;
		$data['node_code']    = $node_info->nodecode;
		$data['controller']   = $controller;
		$data['action'] 	  = $action;
		$data['request_info'] = $request_info;
		$data['action_time']  = date('Y-m-d H:i:s', time());
		$data['remark']       = $remark;
		//添加记录信息到数据库
		DB::table('admin_action')->insert($data);
		return $data;
	}